<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/9/25
 * Time: 23:08
 */

namespace App\Repository;


use App\Model\PermissionRole;
use App\Model\Role;

class PermissionRoleRepository
{
    protected $permissionRole;

    public function __construct(PermissionRole $permissionRole)
    {
        $this->permissionRole = $permissionRole;
    }

    /**
     * 获取所有角色
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function all()
    {
        return Role::all();
    }

    /**
     * 根据role_id找出权限ID
     *
     * @param $roleId
     * @param array $column
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|static[]
     */
    public function findByRole($roleId, $column = ['*'])
    {
        return PermissionRole::where('role_id', $roleId)->get($column);
    }

    /**
     * 根据role_id找出权限
     *
     * @param $roleId
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|static[]
     */
    public function findPermissionByRole($roleId)
    {
        return PermissionRole::with('permission')->where('role_id', $roleId)->get();
    }

    /**
     * 根据role_id更新权限
     *
     * @param $roleId
     * @param array $permissions
     */
    public function updateByRole($roleId, Array $permissions)
    {
        $permissions = array_unique($permissions);

        PermissionRole::whereRoleId($roleId)->delete();

        foreach ($permissions as $permission) {
            PermissionRole::create(['role_id' => $roleId, 'permission_id' => $permission]);
        }
    }
}